import sqlite3

from common.log import log
from settings import  DBSql


class MysqlAuto(object):
    def __init__(self):
        self.conn = sqlite3.connect(DBSql.sql_file)
        self.cursor = self.conn.cursor()
        log.info(f"Connected to database:{DBSql.sql_file}")

    def __del__(self):
        """对象资源被释放时触发"""
        self.cursor.close()
        self.conn.close()
        log.info("Database connection closed.")

    def execute(self, sql_list):
        """执行"""
        try:
            for sql in sql_list:
                log.info(f'sql, {sql}')
                self.cursor.execute(sql)
                result = self.cursor.fetchall()  # 保存最后一次查询的结果
                log.debug(f"SQL执行结果: {result}")
            # 提交事务
            self.conn.commit()
            return result
        except Exception as e:
            log.error(f"SQL执行错误: {e}")
            # 回滚事务
            self.conn.rollback()
            return None  # 发生错误时返回None

if __name__ == '__main__':
    sql = MysqlAuto()
    # sql.execute(['select * from df_user_userinfo'])
    # sql.execute(DBSql.sql_list)
